/*
Copyright Zhigui.com. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

import React, { Component } from 'react'
import { Table, Pagination, Checkbox, Modal, Steps } from 'antd'
import { InfoCircleFilled } from '@ant-design/icons'
import request from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig'
import axios from 'axios'
import moment from 'moment'
import _ from 'lodash'
import Empty from '@/pages/Dashboard/common/Empty/index'
import { checkPermission } from '@/components/AuthComponent/utils'
import AuthComponent from '@/components/AuthComponent'

import './index.less'

const {
  event: { evenrList, eventOperation },
} = address
const CancelToken = axios.CancelToken
const confirm = Modal.confirm
const { Step } = Steps
let cancel

const eventType = {
  ORG_INVITE_JOIN_CONSORTIUM: '联盟邀请',
  USER_INVITE: '联盟邀请',
  ORG_APP_JOIN_CONSORTIUM: '联盟申请',
  consortiumUpdate: '联盟更新',
  CHANNEL_INVITE: '通道邀请',
  CHANGE_STRATEGY: '投票策略投票',
  channelUpdate: '通道更新',
  DELETE_CONSORTIUM: '删除联盟',
  CHANNEL_APPLY: '通道申请',
}
// 状态
// 联盟邀请通道邀请3中情况 投票审批无审批
const eventStatus = {
  SUCCESS: '已通过', // 统一
  FAILED: '失败', // 统一
  REFUSED: '已拒绝',
  PENDING: '处理中',
  SENDING: '处理中',
  TOBE_ACCEPTED: '待接受',
  VOTING: '投票中',
  ACCEPTED: '待审核',
  ACCEPTED_PENDING: '处理中',
  TOBE_ACCEPTED_PENDING: '处理中',
  TOBE_ACCEPTED_FAILED: '已拒绝',
  ACCEPTED_FAILED: '已拒绝',
}

const STATUS = {
  SUCCESS: 'common-success',
  FAILED: 'common-fail',
  REFUSED: 'common-fail',
  PENDING: 'common-ing',
  SENDING: 'common-ing',
  TOBE_ACCEPTED: 'common-ing',
  VOTING: 'common-ing',
  ACCEPTED: 'common-ing',
  ACCEPTED_PENDING: 'common-ing',
  TOBE_ACCEPTED_PENDING: 'common-ing',
  TOBE_ACCEPTED_FAILED: 'common-fail',
  ACCEPTED_FAILED: 'common-fail',
}

@AuthComponent('event')
export default class Event extends Component {
  constructor(props) {
    super(props)
    this.state = {
      eventData: [],
      loading: true,
      visible: false,
      searchValue: '',
      pageNo: 1, // 当前页
      pageSize: 10, // 每页的条数
      url: address.organizationManagement.peerList.format({
        id: '0ca47d59e02c40058834209340009241',
      }),
      statusList: [
        // { id: "USER_INVITE", text: "联盟邀请", checked: false },
        { id: 'ORG_INVITE_JOIN_CONSORTIUM', text: '联盟邀请', checked: false },
        { id: 'ORG_APP_JOIN_CONSORTIUM', text: '联盟申请', checked: false },
        { id: 'consortiumUpdate', text: '联盟更新', checked: false },
        { id: 'DELETE_CONSORTIUM', text: '删除联盟', checked: false },
        { id: 'CHANGE_STRATEGY', text: '投票策略投票', checked: false },
        { id: 'CHANNEL_INVITE', text: '通道邀请', checked: false },
        { id: 'CHANNEL_APPLY', text: '通道申请', checked: false },
        { id: 'channelUpdate', text: '通道更新', checked: false },
      ],
    }
  }
  getEventData = async() => {
    let res = await request().get(evenrList, {
      cancelToken: new CancelToken(function executor(c) {
        cancel = c
      }),
    })

    if (res && res.status === 200 && res.data) {
      this.totalList = res.data || []

      // 处理中事件已经同意和已经拒绝操作按钮置灰
      res.data.map((item) => {
        if (
          item.status.indexOf('PENDING') >= 0 ||
          item.status.indexOf('FAILED') >= 0 ||
          item.status.indexOf('SUCCESS') >= 0
        ) {
          item.action = true
        }
        return item
      })
      this.setState({
        eventData: this.totalList,
        loading: false,
      })
    }
  };

  componentDidMount() {
    this.getEventData()
  }
  monitor = (element) => {
    this.eventData = element
    this.setState({
      visible: true,
    })
  };
  steps = (status, type, vote_strategy) => {
    if (!status) return
    let current = 0
    let _status = 'process'
    let _label1, _label2
    const label1Type = {
      CHANNEL_INVITE: 'TOBE_ACCEPTED_FAILED',
    }

    const stepType = {
      CHANNEL_INVITE: 'TOBE_ACCEPTED',
    }

    const steps = {
      USER_INVITE: 2,
      CHANGE_STRATEGY: 2,
      ORG_INVITE_JOIN_CONSORTIUM: 3,
    }

    let votePercent = vote_strategy + '%' || '70%'
    current =
      status === 'VOTING' && type === 'ORG_INVITE_JOIN_CONSORTIUM'
        ? 1
        : status.indexOf(stepType[type] || 'ACCEPTED') >= 0
          ? 1
          : status === 'SUCCESS' || status === 'FAILED'
            ? steps[type] || 2
            : 0
    _status = status.indexOf('FAILED') >= 0 ? 'error' : 'process'
    _label1 =
      status === (label1Type[type] || 'ACCEPTED_FAILED') ? '拒绝' : '通过'
    _label2 = status === 'FAILED' ? '拒绝' : '通过'
    let stepsObj = {
      // 联盟邀请创建者审批
      USER_INVITE: () => {
        return (
          <Steps
            current={current}
            status={_status}
            labelPlacement="vertical"
            className="step"
          >
            <Step description="发起邀请" />
            <Step description="成员接受邀请" />
            <Step description={'创建者' + _label1 + '审批'} />
            <Step description={'邀请' + _label2} />
          </Steps>
        )
      },
      ORG_INVITE_JOIN_CONSORTIUM: () => {
        let label3 = ''
        let label4 = ''
        if (type === 'ORG_INVITE_JOIN_CONSORTIUM') {
          if (status === 'SUCCESS') {
            label3 = '通过'
            label4 = '通过'
            current = 3
          } else if (status === 'VOTING') {
            label3 = '中'
            label4 = '通过'
            current = 2
          } else {
            label3 = '失败'
            label4 = '拒绝'
            current = 3
          }
        }
        return (
          <Steps
            current={current}
            status={_status}
            labelPlacement="vertical"
            className="step"
          >
            <Step description="发起邀请" />
            <Step description="成员接受邀请" />
            <Step description={'投票' + label3} />
            <Step description={'邀请' + label4} />
          </Steps>
        )
      },
      // 没用到
      // consortiumInvite: () => {
      //     return (
      //         <Steps labelPlacement='vertical' className='step'>
      //             <Step description="发起邀请" />
      //             <Step description="成员接受邀请" />
      //             <Step description="邀请通过" />
      //         </Steps>
      //     )
      // },
      // 联盟邀请投票
      CHANGE_STRATEGY: () => {
        return (
          <Steps
            current={current}
            status={_status}
            labelPlacement="vertical"
            className="step"
          >
            <Step description="发起邀请" />
            {/* <Step description={'成员' + _label1 + '邀请'} /> */}
            <Step description={votePercent + '已投票同意'} />
            <Step description={'邀请' + _label2} />
          </Steps>
        )
      },
      // 没用到
      // channelInvite: () => {
      //     return (
      //         <Steps labelPlacement='vertical' className='step'>
      //             <Step description="发起邀请" />
      //             <Step description="成员接受邀请" />
      //             <Step description="邀请通过" />
      //         </Steps>
      //     )
      // },
      // 联盟申请（创建者审批）
      ORG_APP_JOIN_CONSORTIUM: () => {
        return (
          <Steps
            current={current}
            status={_status}
            labelPlacement="vertical"
            className="step"
          >
            <Step description="发起申请" />
            <Step description={'创建者' + _label1 + '审批'} />
            <Step description={'申请' + _label2} />
          </Steps>
        )
      },
      // 通道邀请创建者审批
      CHANNEL_INVITE: () => {
        return (
          <Steps
            current={current}
            status={_status}
            labelPlacement="vertical"
            className="step"
          >
            <Step description="发起邀请" />
            <Step description={'成员' + _label1 + '邀请'} />
            {/* <Step description={'创建者' + _label1 + '审批'} /> */}
            <Step description={'邀请' + _label2} />
          </Steps>
        )
      },
      // 通道申请
      CHANNEL_APPLY: () => {
        return (
          <Steps
            current={current}
            status={_status}
            labelPlacement="vertical"
            className="step"
          >
            <Step description="发起申请" />
            <Step description={votePercent + '已投票同意'} />
            <Step description={'邀请' + _label2} />
          </Steps>
        )
      },
      // 没用到
      // channelInvitevote: () => {
      //     return (
      //         <Steps labelPlacement='vertical' className='step'>
      //             <Step description="发起邀请" />
      //             <Step description="成员接受邀请" />
      //             <Step description={current > 2 ? '投票结束' + votePercent + '已投票同意' : votePercent + '投票通过邀请'} />
      //             <Step description="邀请通过" />
      //         </Steps>
      //     )
      // },
      default: () => {
        return (
          <Steps labelPlacement="vertical" className="step">
            <Step description="发起申请" />
            <Step
              description={
                current > 1
                  ? '投票结束' + votePercent + '已投票同意'
                  : votePercent + '投票通过申请'
              }
            />
            <Step description="申请通过" />
          </Steps>
        )
      },
    }
    return stepsObj[`${type}`] ? stepsObj[`${type}`]() : stepsObj.default()
  };
  // 筛选，排序功能
  handleTableChange = (pagination, filters, sorter) => {
    let filterList = []
    let totalList = this.totalList || []

    const getFilterList = (flag) => {
      let selectList = this.state[flag]
        .filter((element) => {
          return element.checked === true
        })
        .map((element) => {
          return element.id
        })
      return {
        list: selectList.length
          ? selectList
          : this.state[flag].map((element) => {
            return element.id
          }),
      }
    }

    let pageNo = this.state.pageNo
    let filterStatusListTotal = getFilterList('statusList')

    totalList.forEach((element) => {
      filterStatusListTotal.list.includes(element.type) &&
        filterList.push(element)
    })
    if (filterList.length < this.state.pageNo * this.state.pageSize) {
      pageNo = Math.ceil(filterList.length / this.state.pageSize) || 1
    }
    this.setState(
      {
        pageNo: pageNo,
      },
      () => {
        this.setState({
          eventData: filterList,
        })
      }
    )
  };

  componentWillUnmount() {
    cancel && cancel()
    this.setState = () => {
      return
    }
  }

  // 同意or拒绝
  action = (flag, index, operate, id) => {
    let params = {
      approved: '同意',
      rejected: '拒绝',
    }
    confirm({
      title: `是否${params[flag]}该事件？`,
      icon: <InfoCircleFilled />,
      getContainer: () => document.getElementById('event-page'),
      onOk: () => {
        request()
          .post(eventOperation.format({ eventId: id }), {
            operation: operate,
          })
          .then((res) => {
            if (res.status === 200) {
              this.getEventData(index, flag)
              // let { eventData } = this.state;
              // eventData[index].action = flag
              // this.setState({
              //     eventData
              // })
            }
          })
      },
      className: 'actionModal',
    })
  };
  // 筛选下拉列表
  dropDown = (setSelectedKeys, clearFilters, confirm) => {
    return (
      <div>
        <div className="ant-dropdown-menu">
          {this.state.statusList.map((element, index) => {
            return (
              <li
                className="ant-dropdown-menu-item"
                key={element.text}
                style={{ background: element.checked ? '#E9F5FF' : '#fff' }}
                onClick={() =>
                  this.selectLevel(
                    element,
                    index,
                    'statusList',
                    setSelectedKeys
                  )
                }
              >
                <Checkbox checked={element.checked}>
                  {' '}
                  <span style={{ color: '#171E2D' }}>{element.text}</span>
                </Checkbox>
              </li>
            )
          })}
        </div>
        <div className="ant-table-filter-dropdown-btns">
          <span
            className="clear"
            onClick={() => this.clear(clearFilters, 'statusList')}
          >
            重置
          </span>
          <span className="confirm" onClick={() => this.confirm(confirm)}>
            确定
          </span>
        </div>
      </div>
    )
  };
  // 筛选的勾选操作
  selectLevel = (level, index, flag, setSelectedKeys) => {
    // 设置选择的key
    this.level = _.cloneDeep(level)
    let data = this.state[flag]

    data[index].checked = !level.checked

    this.setState({
      [flag]: data,
    })
    setSelectedKeys(
      data.filter((element) => {
        return element.checked === true
      })
    )
  };
  // 手动确定
  confirm = (confirm) => {
    confirm && confirm()
  };
  // 重置 重置为初始状态
  clear = (clear, flag) => {
    let data = this.state[flag]
    data.forEach((element) => {
      element.checked = false
    })
    this.setState(
      {
        [flag]: data,
      },
      clear
    )
  };

  onShowSizeChange = (current, pageSize) => {
    let pageNo = this.state.pageNo
    if (this.state.eventData.length < pageNo * pageSize) {
      pageNo = Math.ceil(this.state.eventData.length / pageSize) || 1
    }
    this.setState({
      pageSize,
      pageNo,
    })
  };

  changePaginationFn = (pageNumber) => {
    this.setState({
      pageNo: pageNumber,
    })
  };

  search = () => {
    this.setState({
      searchValue: this.searchValue,
    })
  };

  changeValueFn = (e) => {
    this.searchValue = e.target.value
  };

  getDetail = async(record) => {
    this.record = record
    this.setState({
      visible: true,
    })
  };

  isAllowedFn = (record) => {
    let isHandler = record.isHandler || 0 // 是否有权利投票
    let progressStatus = record.progressStatus || '' // 投票的状态

    let flag = false
    if (isHandler && progressStatus === 'VOTING') {
      flag = true
    }
    if (
      record.type === 'CHANNEL_INVITE' &&
      record.status === 'TOBE_ACCEPTED' &&
      record.isInvitee &&
      record.isInvitee === 1
    ) {
      flag = true
    }
    if (record.status === 'FAILED' || record.status === 'SUCCESS') {
      flag = false
    }
    return flag
  };

  render() {
    let list = []

    this.state.eventData.map((element) => {
      let keyWord = this.searchValue
      let name = keyWord ? element.eventName.match(keyWord.trim()) : true
      name && list.push(element)
    })

    const columns = [
      {
        title: '事件名称',
        dataIndex: 'eventName',
        key: 'eventName',
        width: '35%',
        render: (text) => {
          return (
            // <Tooltip placement="topLeft" title={text}>
            //     <div>{text && text.length > 30 ? `${text.slice(0, 30)}...` : text}</div>
            // </Tooltip>
            <div>{text}</div>
          )
        },
      },
      {
        title: '事件发起者',
        dataIndex: 'initName',
        key: 'initName',
        width: '25%',
        render: (text, record) => {
          return (
            // <Tooltip placement="topLeft" title={text}>
            //     <div>{text && text.length > 15 ? `${text.slice(0, 15)}...` : text}</div>
            // </Tooltip>
            <div>{text}</div>
          )
        },
      },
      {
        title: '事件类型',
        key: 'type',
        dataIndex: 'type',
        className: 'status',
        width: '15%',
        onFilterDropdownVisibleChange: (visible) => {
          if (
            document.getElementsByClassName('status') &&
            document.getElementsByClassName('status').length
          ) {
            document.getElementsByClassName(
              'status'
            )[0].style.backgroundColor = visible ? '#F1F3F4' : '#F8F8F8'
          }
        },
        filterDropdown: ({
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
        }) => {
          return this.dropDown(setSelectedKeys, clearFilters, confirm)
        },

        render: (text, record, index) => {
          return <div>{eventType[text]}</div>
        },
      },
      {
        title: '状态',
        key: 'status',
        dataIndex: 'status',
        width: '10%',
        render: (text, record) => (
          <span className={STATUS[text]}>{eventStatus[`${text}`]}</span>
        ),
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record, index) => {
          return (
            <div
              className={
                this.isAllowedFn(record) ? 'action' : 'action notAllowed'
              }
            >
              {
                checkPermission('event-agree') &&
                <span
                  onClick={() =>
                    this.isAllowedFn(record) &&
                  this.action('approved', index, true, record.id)
                  }
                >
                同意
                </span>
              }
              {
                checkPermission('event-refuse') &&
                <span
                  onClick={() =>
                    this.isAllowedFn(record) &&
                  this.action('rejected', index, false, record.id)
                  }
                >
                拒绝
                </span>
              }

              <span onClick={() => this.getDetail(record)}>详情</span>
            </div>
          )
        },
      },
    ]
    return (
      <div id="event-page" className="event-page common">
        <Modal
          title="事件详情"
          visible={this.state.visible}
          footer={null}
          forceRender
          centered={true}
          onCancel={() => this.setState({ visible: false })}
          className="event-modal"
          width={663}
        >
          <div className="detail-list">
            <div className="detail-item">
              <div className="detail-item-title">事件名称</div>
              <div className="detail-item-description">
                {_.get(this.record, 'eventName')}
              </div>
            </div>
            <div className="detail-item">
              <div className="detail-item-title">事件类型</div>
              <div className="detail-item-description">
                {eventType[_.get(this.record, 'type')]}
              </div>
            </div>
            <div className="detail-item">
              <div className="detail-item-title">发起时间</div>
              <div className="detail-item-description">
                {_.get(this.record, 'createTime')
                  ? moment(_.get(this.record, 'createTime')).format(
                    'YYYY-MM-DD HH:mm:ss'
                  )
                  : '暂无数据'}
                {/* {this.record.createTime ? moment(this.record.createTime).format('YYYY-MM-DD HH:mm:ss') : '暂无数据'} */}
              </div>
            </div>
            <div className="detail-item">
              <div className="detail-item-title">结束时间</div>
              <div className="detail-item-description">
                {_.get(this.record, 'finishTime')
                  ? moment(_.get(this.record, 'finishTime')).format(
                    'YYYY-MM-DD HH:mm:ss'
                  )
                  : '暂无数据'}

                {/* {this.record.finishTime ? moment(this.record.finishTime).format('YYYY-MM-DD HH:mm:ss') : '暂无数据'} */}
              </div>
            </div>
          </div>
          <div>
            <div className="event-result">事件处理情况</div>
            {this.steps(
              _.get(this.record, 'status'),
              _.get(this.record, 'type'),
              _.get(this.record, 'vote_strategy')
            )}
          </div>
        </Modal>
        <div className="container">
          <div className="table-list">
            {/* 列表*/}
            <div className="peer_wrapper">
              <Table
                columns={columns}
                getPopupContainer={(node) => {
                  if (node) {
                    return node.parentNode
                  }
                  return document.body
                }}
                onChange={this.handleTableChange}
                className={list.length ? '' : 'empty-list'}
                dataSource={
                  list.length
                    ? list.slice(
                      (this.state.pageNo - 1) * this.state.pageSize,
                      this.state.pageNo * this.state.pageSize
                    )
                    : []
                }
                rowKey="id"
                pagination={false}
              />
              {list.length ? null : <Empty />}
            </div>
            <div className="pagination-box">
              {/* 总数*/}
              {this.state.eventData.length ? (
                <Pagination
                  current={this.state.pageNo}
                  pageSize={this.state.pageSize}
                  total={this.state.eventData.length}
                  showSizeChanger
                  showQuickJumper
                  onShowSizeChange={this.onShowSizeChange}
                  onChange={this.changePaginationFn}
                />
              ) : null}
            </div>
          </div>
        </div>
      </div>
    )
  }
}
